import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { BiStatus } from '@/common/type/BiStatus';
import { list, add, update, remove } from '@/services/product';

export interface Product {
  id?: number;
  brandOption?: { key: Product['brandId']; label: Product['brandName'] };
  brandId?: number;
  brandName?: string;
  productCategoryIds?: number[];
  productCategoryId?: number;
  subTitle?: string;
  description?: string;
  pic?: string;
  name?: string;
  price?: number;
  originalPrice?: number;
  stock?: number;
  unit?: string;
  weight?: number;
  productSn?: string;
  sale?: number;
  publishStatus?: BiStatus;
  verifyStatus?: BiStatus;
  newStatus?: BiStatus;
  recommendStatus?: BiStatus;
  giftPoint?: number;
  giftGrowth?: number;
  usePointLimit?: number;
  previewStatus?: BiStatus;
  serviceIds?: number[];
  detailTitle?: string;
  detailDesc?: string;
}

export interface ProductModelState {
  products: Product[];
}

export interface ProductModelType extends Model {
  namespace: 'product';
  state: ProductModelState;
  effects: {
    query: Effect;
    add: Effect;
    update: Effect;
    remove: Effect;
  };
  reducers: {
    refresh: Reducer<ProductModelState>;
  };
}

const ProductModel: ProductModelType = {
  namespace: 'product',
  state: {
    products: [],
  },

  reducers: {
    refresh(state, action) {
      return {
        ...state,
        products: action.products,
      };
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({
        type: 'refresh',
        products: response,
      });
    },
    *add({ payload, callback }, { call, put }) {
      yield call(add, payload);
      yield put({
        type: 'query',
      });
      callback();
    },
    *update({ payload }, { call, put }) {
      yield call(update, payload);
      yield put({
        type: 'query',
      });
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put({
        type: 'query',
      });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/product/list') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default ProductModel;
